#!/usr/bin/env bash

# Copyright 2021 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetesValidating:
- name: ingressnginxcontrollers-policy.deckhouse.io
  group: main
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["v1"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["ingressnginxcontrollers"]
    scope:       "Cluster"
EOF
}

function forbid() {
  jq -nc --arg message "$1" '
    {
      "allowed": false,
      "message": $message
    }
    ' > $VALIDATING_RESPONSE_PATH
}

function __main__() {
  # Inlet on-flight change prohibited
  if context::jq -e -r '.review.request.operation == "UPDATE"' >/dev/null 2>&1; then
    oldInlet=$(context::jq -r '.review.request.oldObject.spec.inlet')
    if context::jq -e -r --arg oldInlet "$oldInlet" '.review.request.object.spec.inlet != $oldInlet' >/dev/null 2>&1; then
      forbid ".spec.inlet field is immutable"
      exit 0
    fi
  fi

  if context::jq -e -r '.review.request.name | endswith("-failover")' >/dev/null 2>&1; then
    # -failover suffix is reserved for HostWithFailover inlet
    # To avoid collisions, we should forbid saving controllers with such name.
    forbid ".metadata.name ends with reserved suffix \"-failover\""
    exit 0
  fi

  if defaultSSLSecret=( $(context::jq -re '.review.request.object.spec.defaultSSLCertificate.secretRef // empty | .namespace, .name') ); then
    if ! kubectl get secret -n ${defaultSSLSecret[0]} ${defaultSSLSecret[1]} >/dev/null 2>&1; then
      forbid ".spec.defaultSSLCertificate field contains reference to non existent Secret \"${defaultSSLSecret[0]}/${defaultSSLSecret[1]}\""
      exit 0
    fi
  fi

  # Allowed response.
  jq -nc '{"allowed": true}' > $VALIDATING_RESPONSE_PATH
}

hook::run "$@"
